//
//  MeRegisterVC.m
//  OC_Poj_demo
//
//  Created by weixin on 2018/7/20.
//  Copyright © 2018年 weixn. All rights reserved.
//

#import "MeRegisterVC.h"
#import "MeImportCode.h"
//#import "OKGetCodeBtn.h"
#import "NumberKeyboard.h"
#import <TCWebCodesSDK/TCWebCodesBridge.h>

@interface MeRegisterVC ()<UITextViewDelegate>

@property (weak, nonatomic) IBOutlet BaseBtn *codeBtn;

@property (nonatomic,strong)UITextView *textView;

@property (nonatomic,strong)BaseLab *placeholderLab;//输入手机号提示

@property (nonatomic,strong)BaseLab *redTipe;//报错提示

@end

@implementation MeRegisterVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.'
    
    [self setNav];
    
    [self setUI];
    [self.textView becomeFirstResponder];

//    [RACObserve(self.textView, editable)subscribeNext:^(id  _Nullable x) {
//        if (self.textView.editable) {
//           self.textView
//        }else{
//
//        }
//    }];
}

-(void)setNav{
    [self.baseNavigationView setHiddenNav:NO VC:self];

    /* TODO: ================= 导航栏V4样式 =================*/
    [self.baseNavigationView NavigationBarStyle:1];
    self.baseNavigationView.navViewStyle.title.text = @"登录或注册";
    self.baseNavigationView.leftButton1.hidden = YES;
    self.baseNavigationView.navViewStyle.isShowShadow = NO;
    self.baseNavigationView.bottomLineView.hidden = YES;
    //登录或注册
//    [self.baseNavigationView setBackgroundColor:[UIColor clearColor]];
//    self.baseNavigationView.bottomLineView.backgroundColor = [UIColor clearColor];
//    [UIColor setDefaulGradiennBackgroundColors:self.view];
//    self.tabBarController.tabBar.hidden = YES;
//    self.baseNavigationView.leftButton1.hidden = YES;
//
//    BaseBtn *btn = [[BaseBtn alloc]initializeFrame:CGRectMake(20, 40, 30, 30) NormalText:nil NormalTextColor:nil SeleText:nil NormalImage:@"common_back_white" SeleImage:nil SeleTextColor:nil font:nil isBold:nil];
//    @weakify(self);
//    [[btn rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
//        @strongify(self);
//        [self.navigationController popViewControllerAnimated:YES];
//    }];
//
//    [self.view addSubview:btn];
}

-(void)setUI{
    
//    QMUILabel *leb = [[QMUILabel alloc]initWithFrame:CGRectMake(20,80, 150, 40)];
//    leb.text = @"登录或注册";
//    leb.font = [UIFont systemFontOfSize:25];
//    leb.textColor = [UIColor whiteColor];
//    [self.view addSubview:leb];
//
//    QMUILabel *leb1 = [[QMUILabel alloc]initWithFrame:CGRectMake(25,150, 150, 20)];
//    leb1.text = @"输入手机号码";
//    leb1.font = [UIFont systemFontOfSize:12];
//    leb1.textColor = [UIColor whiteColor];
//    [self.view addSubview:leb1];
    

    
    [self.view addSubview:self.textView];
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(80+NaviHeight);
        make.left.mas_equalTo(10);
        make.width.mas_equalTo(kScreenW-20);
        make.height.mas_equalTo(40);
    }];
    
    
    [self.view addSubview:self.redTipe];
    [self.redTipe mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.textView.mas_bottom).offset(25);
        make.left.equalTo(self.view).offset(15);
    }];
    
    [self.view addSubview:self.placeholderLab];
    [self.placeholderLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.textView.mas_bottom).offset(-5);
        make.left.equalTo(self.view).offset(10);
    }];
    
    [self.codeBtn setCornerRadiusWithRadius:4 isMasks:YES];
    [self.codeBtn setBorderWithColor:baseColorTheme width:1];
    [self.codeBtn setTitleColor:baseColorTheme forState:UIControlStateNormal];
    self.codeBtn.alpha = 0.4;

    [self addLine];

}

-(void)addLine{
    BaseView *viewLine = [[BaseView  alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    viewLine.backgroundColor = [UIColor colorWithHex:@"eeeeee"];
    [self.view addSubview:viewLine];
    
    [viewLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.textView.mas_bottom).offset(15);
        make.left.equalTo(self.view).offset(15);
        make.right.equalTo(self.view).offset(-15);
        make.height.mas_equalTo(1);
    }];
}


- (IBAction)Code:(id)sender {
    
    /* FIXME: ================= 键盘有个点击事件  所以按钮需要点两下才能登录 ================= */
    [self.view endEditing:YES];


    if (self.textView.text.length == 11) {
                
        if ([NSString Mobile:self.textView.text]) {
            @weakify(self);
            
            /**
             @param appid，在验证码接入平台注册申请；
             @param callback，为回调函数，验证码验证完成后回调该函数将结果带回
             */

            [[TCWebCodesBridge sharedBridge]loadTencentCaptcha:self.view appid:@"2097119585" callback:^(NSDictionary *resultJSON) {
                if(0==[resultJSON[@"ret"] intValue]) {
                    /**
                     验证成功
                     返回内容：
                     resultJSON[@"appid"]为回传的业务appid
                     resultJSON[@"ticket"]为验证码票据
                     resultJSON[@"randstr"]为随机串
                     */

                    NSLog(@"");
                    [[AccountService loadLoginForsendCode:self.textView.text ticket:resultJSON[@"ticket"] randstr:resultJSON[@"randstr"] reponseObjctClass:nil]subscribeNext:^(ResponseData * x) {
                        
                        if (x.success) {
                            //                    [self.codeBtn timeFailBeginFrom:45];
                            //                    self.codeBtn.alpha = 0.3;
                            //                    [self.codeBtn setTitle:@"剩余45S" forState:UIControlStateNormal];
                            MeImportCode *vc = [[MeImportCode alloc]init];
                            vc.phoneNumber = self.textView.text;
                            
                            [self.navigationController pushViewController:vc animated:YES];
                        }else{
                            [Tools showTips:x.errorInfo];
                        }
                    }];
                } else {
                    [Tools showTips:@"验证验证码校验失败"];

                    /**
                     验证失败
                     返回内容：
                     ret=-1001为验证码js加载错误
                     ret=-1002一般为网络错误
                     ret=-1为返回票据数据解析错误，业务可根据需要重试处理
                     ret的其他返回值，为验证失败，比如用户主动关闭了验证码弹框
                     */
                }
            }];
     

//            [[AccountService loadSendSms:self.textView.text]subscribeNext:^(ResponseData* x) {
//                @strongify(self);
//
//
//            }];
            
        }else{
            self.redTipe.hidden = NO;
            self.redTipe.text = @"手机格式不正确";
//            [Tools showTips:@"手机格式不正确"];
            
        }
        
    }else{
        self.redTipe.hidden = NO;
        self.redTipe.text = @"手机号码长度不正确";
//        [Tools showTips:@"手机号码长度不正确"];
        
    }
}



/** 键盘背景色 适合于自定义键盘颜色 */
//- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoBoardHidden:) name:UIKeyboardWillShowNotification object:nil];
//    return YES;
//}
//
//- (void)keyBoBoardHidden:(NSNotification *)Notification{
//    [self.tf becomeFirstResponder];
//    [self setHiddenBackView];
//}
//
//-(void)setHiddenBackView{
//    NSArray *arrTitle = @[@"UIRemoteKeyboardWindow",@"UIInputSetContainerView",@"UIInputSetHostView",@"UIView",@"UIKBInputBackdropView",@"UIKBBackdropView",@"_UIBackdropEffectView",@"UIView"];
//
//    NSArray *arr = [[UIApplication sharedApplication]windows];
//
//    int i = 0 ;
//
//    for (UIWindow *w in arr) {
//        if([[NSString stringWithUTF8String:object_getClassName((w))] isEqualToString:arrTitle[i]]){
//            NSArray *arr1 = [w subviews];
//            i++;
//            for (UIView * v1 in arr1) {
//                if([[NSString stringWithUTF8String:object_getClassName((v1))] isEqualToString:arrTitle[i]]){
//                    i++;
//                    if ([self setArrM:arrTitle[i] view:v1]) {
//
//                        UIView *v2 = [self setArrM:arrTitle[i] view:v1];
//                        for (int j =0; j<arrTitle.count-4; j++) {
//                            i++;
//                            v2 = [self setArrM:arrTitle[i] view:v2];
//                        }
//                    }
//                }
//            }
//        }
//    }
//}
//
//-(UIView*)setArrM:(NSString*)name view:(UIView*)v{
//    NSArray *arr = v.subviews;
//    for (UIView *v1 in arr) {
////        NSLog(@"v ====  %@",[NSString stringWithUTF8String:object_getClassName(v1)]);
//
//        if ([[NSString stringWithUTF8String:object_getClassName((v1))] isEqualToString:@"_UIBackdropEffectView"]) {
//            v1.hidden = YES;
//        }
//
//        if ([[NSString stringWithUTF8String:object_getClassName((v1))] isEqualToString:@"UIView"]) {
//            v1.hidden = YES;
//        }
//
//        if([[NSString stringWithUTF8String:object_getClassName((v1))] isEqualToString:name]){
//            return v1;
//        }
//    }
//
//    return nil;
//
//}
- (UITextView *)textView{
    if (!_textView) {
        _textView = [[UITextView alloc]init];
        _textView.font = [UIFont systemFontOfSize:12];
        _textView.delegate = self;
        _textView.layer.cornerRadius = 5;
        _textView.enablesReturnKeyAutomatically = YES;
        _textView.tintColor = baseColorLight;
        _textView.keyboardType = UIKeyboardTypeNumberPad;
//        _textView.qmui_borderPosition = QMUIViewBorderPositionBottom;
//        _textView.qmui_borderWidth = 1;
//        _textView.qmui_borderColor = baseColorLight;
//        _textView.keyboardAppearance = UIKeyboardAppearanceDark;
        _textView.font = [UIFont fontWithName:@"PingFangSC-Medium" size:28];
        // 限制可输入的字符长度
        _textView.maximumZoomScale = 8;//设置最大缩放
        
    }
    return _textView;
}

- (void)textViewDidChange:(UITextView *)textView
{
    if (textView.text.length > 11)
    {
        textView.text = [textView.text substringToIndex:11];
    }
    self.redTipe.hidden = YES;
    //记录输入的字数，你若不统计字数，忽略这行
    //    self.limitWordLable.text = [NSString stringWithFormat:@"%lu/%d", (unsigned long)[textView.text length], 200];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    self.placeholderLab.hidden = YES;
    /** 限制字数 10个 */
    NSString *str = [NSString stringWithFormat:@"%@%@", textView.text, text];
    if (str.length>0) {
        self.codeBtn.alpha = 1;
    }else{
        self.codeBtn.alpha = 0.4;
    }
    if (str.length > 11)
    {
        NSRange rangeIndex = [str rangeOfComposedCharacterSequenceAtIndex:11];
        
        if (rangeIndex.length == 1)//字数超限
        {
            textView.text = [str substringToIndex:11];
        }else{
            NSRange rangeRange = [str rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, 11)];
            textView.text = [str substringWithRange:rangeRange];
        }
        return NO;
    }
    return YES;
}

-(BaseLab *)placeholderLab{
    if (!_placeholderLab) {
        _placeholderLab = [[BaseLab alloc]initializeFrame:CGRectMake(0, 0, 1, 1) text:@" 请输入手机号" font:28 textColor:[UIColor colorWithHex:@"999999"] isBold:NO numberOfLines:0];
        _placeholderLab.font = [UIFont fontWithName:@"PingFang-SC-Regular" size:28];
    }
    return _placeholderLab;
}

-(BaseLab *)redTipe{
    if (!_redTipe) {
        _redTipe = [[BaseLab alloc]initializeFrame:CGRectMake(0, 0, 1, 1) text:@"输入手机号错误" font:12 textColor:[UIColor colorWithHex:@"FF6F6F"] isBold:NO numberOfLines:0];
        _redTipe.font = [UIFont fontWithName:@"PingFangSC-Medium" size:12];
        _redTipe.hidden = YES;
    }
    return _redTipe;
}



@end
